﻿using System;
using System.Threading;
using Host;
using System.Reflection;

namespace TheHost
{
	class MainClass
	{
		public static void Main(string[] args)
		{
			EventTools.GetInstance().TriggerEvent("LoadDll");
			EventTools.GetInstance().TriggerEvent("SystemStart");

			//创建合适的对象
			var host = new Host.Host();

			//加载项目中的所有合适的类
            var item_calss = Assembly.Load("Example");
			foreach (var item in item_calss.GetTypes())
			{
				if (item.IsSubclassOf(typeof(IComponents))) 
				{
					ComponentsFactory.GetInstance().RegisterProvider(item.Name, () => { return (IComponents)item_calss.CreateInstance(item.FullName); });

					try
					{
						host.AddComponents((IComponents)item_calss.CreateInstance(item.FullName));
					}
					catch (Exception ex)
					{
						Console.WriteLine(ex.Message);
					}
				}
			}


			HostManager.GetInstance().AddHost(host);



			bool runing = true;

			var thread = new Thread(() => {
				while (runing)
				{
					HostManager.GetInstance().Update();
					Thread.Sleep(HostManager.GetInstance().GetHostCount() > 0 ? 100 : 1000);
				}

				runing = false;
			});
			thread.IsBackground = true;
			thread.Start();

			EventTools.GetInstance().TriggerEvent("MainThreadStart");

			while (true)
			{
				string userinput = Console.ReadLine();

				if (userinput == "exit")
				{
					break;
				}

				var func = UserInputHandleManager.GetInstance().GetHanlde(userinput);
				if (func != null)
				{
					func();
				}
				else
				{
					Console.WriteLine("Not Find Hanlde For " + userinput);
				}
			}

			EventTools.GetInstance().TriggerEvent("SystemWillStop");

			runing = false;
			while (thread.ThreadState == ThreadState.Running)
			{
				Thread.Sleep(100);
			}

			EventTools.GetInstance().TriggerEvent("SystemStop");
		}
	}
}
